/**
 *  Copyright 2012 Rafal Korytkowski
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.googlecode.rapidjunit.builder;

import java.util.Arrays;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

/**
 * Represents a nature that indicates whether {@link RapidJUnitBuilder} should be used or not for
 * the given Eclipse project.
 * 
 * @author Rafal Korytkowski
 */
public class RapidJUnitNature implements IProjectNature {
	
	/**
	 * ID of this project nature
	 */
	public static final String NATURE_ID = "com.googlecode.rapidjunit.builder.RapidJUnitNature";
	
	private IProject project;
	
	@Override
	public void configure() throws CoreException {
		IProjectDescription desc = project.getDescription();
		
		ICommand[] commands = desc.getBuildSpec();
		for (int i = 0; i < commands.length; i++) {
			if (commands[i].getBuilderName().equals(RapidJUnitBuilder.BUILDER_ID)) {
				return;
			}
		}
		
		ICommand command = desc.newCommand();
		command.setBuilderName(RapidJUnitBuilder.BUILDER_ID);
		
		ICommand[] newCommands = Arrays.copyOf(commands, commands.length + 1);
		newCommands[commands.length] = command;
		
		desc.setBuildSpec(newCommands);
		project.setDescription(desc, null);
	}
	
	@Override
	public void deconfigure() throws CoreException {
		IProjectDescription description = getProject().getDescription();
		
		ICommand[] commands = description.getBuildSpec();
		for (int i = 0; i < commands.length; i++) {
			if (commands[i].getBuilderName().equals(RapidJUnitBuilder.BUILDER_ID)) {
				commands[i] = commands[commands.length - 1];
				ICommand[] newCommands = Arrays.copyOf(commands, commands.length - 1);
				
				description.setBuildSpec(newCommands);
				project.setDescription(description, null);
				return;
			}
		}
	}
	
	@Override
	public IProject getProject() {
		return project;
	}
	
	@Override
	public void setProject(IProject project) {
		this.project = project;
	}
	
}
